// 导入express模块
var express = require('express')
// 创建一个express实例
var app = express();
// 导入nodejs-websocket模块
const ws = require('nodejs-websocket')
// 存储视频文件所需模块
const { Buffer } = require('buffer')
const fs = require('fs')
const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg');
const ffmpeg = require('fluent-ffmpeg');

let screen_cnt = 0;     // 记录录屏socket连接的序号
let camera_cnt = 0;     // 记录摄像头socket连接的序号

ffmpeg.setFfmpegPath(ffmpegInstaller.path);

// 使用静态资源文件
app.use('/static', express.static('static'))

// 执行app的get请求处理，这里访问的是根目录 
app.get('/', function (req, res) {
    console.log("new http req, from", req.ip)
    res.sendFile(__dirname + "/pages/" + "index.html");
})

// 开始监听http请求
app.listen(8081, () => {
    console.log("Please conn 192.168.80.3:8081")
})

// 将webm转为mp4
function webmToMp4(file_name) {
    // webm转mp4
    let command = ffmpeg(file_name + '.webm')
    command.on('start', function (str) {
        console.log('start trans webm to mp4...', str)
        console.log('please waiting...')
    })
    command.on('progress', function (progress) {
        console.log("trans " + file_name + " ing...", progress.timemark)
    })
    command.on('end', function (str) {
        console.log('trans to mp4 done! filename = ', file_name + '.mp4', str)
        fs.unlinkSync(file_name + '.webm')
    })
    command.save(file_name + '.mp4')
}

// 处理连接
// 接收信息，写入流文件
function handleConn(conn, file_name) {
    //创建一个流
    let writerStream = fs.createWriteStream(file_name + '.webm', { flags: 'w' });
    //处理客户端发送过来的消息
    conn.on("binary", (inStream) => {
        inStream.on("readable", () => {
            // 突然发现似乎不需要使用data拼接，每次写入流就好了
            let newData = inStream.read()
            if (newData)
                writerStream.write(newData);
        })
    })
    conn.on("close", (code, reason) => {
        console.log("Connection closed")
        // console.log(code, reason)
        setTimeout(() => {
            writerStream.end();
            console.log("write end")
            webmToMp4(file_name)
        }, 1000);   // 设置定时器防止最后一组传递失败
    })
}

// 执行websocket处理连接方法
ws.createServer(function (conn) {
    console.log('new record screen conn...')
    ++screen_cnt
    let file_name = screen_cnt + '_screen'
    handleConn(conn, file_name)
}).listen(3000)

// 执行websocket处理连接方法
ws.createServer(function (conn) {
    console.log('new record camera conn...')
    ++camera_cnt
    let file_name = camera_cnt + '_camera'
    handleConn(conn, file_name)
}).listen(3001)